package com.yoooya.base.admin.controller.system;

import com.alibaba.fastjson.JSONObject;
import com.yoooya.base.admin.controller.AbstractController;
import com.yoooya.base.admin.interceptor.SessionContext;
import com.yoooya.base.admin.utils.ShiroUtils;
import com.yoooya.base.commons.CommonUtils;
import com.yoooya.base.model.po.call.CallSeatPo;
import com.yoooya.base.model.po.system.SysMenuPo;
import com.yoooya.base.model.po.system.UserInfoPo;
import com.yoooya.base.model.qo.system.SysMenuQo;
import com.yoooya.base.model.vo.BaseResp;
import com.yoooya.base.model.vo.LoginUser;
import com.yoooya.base.service.call.CallSeatService;
import com.yoooya.base.service.system.SysMenuService;
import com.yoooya.base.utils.IdUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.DefaultSessionKey;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * cjianquan 2019/11/11
 */
@Controller
@RequestMapping("/system/login")
public class LoginController extends AbstractController  {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private CallSeatService callSeatService;


    @Override
    public String getSelfBasePath() {
        return "/";
    }


    @RequestMapping(value = "login")
    @ResponseBody
    public Object login(@ModelAttribute("user")LoginUser user, HttpServletRequest request) {
        BaseResp resp = new BaseResp();

        String access_token = ""+ IdUtils.id();
        JSONObject jsonObject = new JSONObject();

//        user.setUserName("chenjianquan");
//        user.setPassword("f7037548f0ce3bcd902aabb8f13e6621");

        /**
         * 使用Shiro编写认证操作
         */

        //3.执行登录方法
        try {
            //1.获取Subject
            Subject subject = SecurityUtils.getSubject();
            //2.封装用户数据
            UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),CommonUtils.md5(user.getPassword()));
            subject.login(token);
            jsonObject.put("access_token",access_token);
            jsonObject.put("user",rtnUser((UserInfoPo)subject.getPrincipal()));
            resp.setData(jsonObject);
        } catch (UnknownAccountException e) {
            resp.setSuccess(false);
            resp.setMsg(e.getMessage());
            e.printStackTrace();
        } catch (IncorrectCredentialsException e) {
            resp.setSuccess(false);
            resp.setMsg(e.getMessage());
            e.printStackTrace();
        }catch (Exception e){
            resp.setSuccess(false);
            resp.setMsg("系统异常，请稍后再试");
            e.printStackTrace();
        }
        return resp;
    }

    private JSONObject rtnUser(UserInfoPo userInfoPo) throws Exception{
        JSONObject json = new JSONObject();
        Long id = userInfoPo.getId();
        json.put("id",id);
        json.put("userName",userInfoPo.getUserName());
        json.put("name",userInfoPo.getName());
        json.put("department",userInfoPo.getDepartment());
        json.put("departmentIds",userInfoPo.getDepartmentIds());
        json.put("role",userInfoPo.getRole());
        json.put("roleIds",userInfoPo.getRoleIds());
        json.put("mobile",userInfoPo.getMobile());
        json.put("portrait",userInfoPo.getPortrait());

        //cjianquan 2020/2/14 以下是坐席信息
        int seatStatus = 0;
        CallSeatPo seat = callSeatService.queryByUser(id);
        if(seat!=null && seat.getChannelId() != null){
            seatStatus = 1;
            if (seat.getStatus() != 1) {
                seatStatus = -1;
            }
            /*boolean isExceed = callRecordService.isExceedNumber(seat.getChannelId());
            if (isExceed) {
                seatStatus = -1;
            }*/
            json.put("channelId",seat.getChannelId());
            json.put("channelPwd",seat.getPassword());
            json.put("seatHost",seat.getIp());
            json.put("seatPort",seat.getPort());
            json.put("seatType",seat.getSeatType()!=null?seat.getSeatType():1);
        }
        json.put("seatStatus",seatStatus);
        return json;
    }


    @RequestMapping(value = "logout")
    @ResponseBody
    public Object logout() {
        BaseResp resp = new BaseResp();
        ShiroUtils.logout();
        return resp;
    }

    @RequestMapping(value = "isLogin")
    @ResponseBody
    public Object isLogin(){
        BaseResp resp = new BaseResp();
        try{
            boolean flag = ShiroUtils.isLogin();
            resp.setSuccess(flag);
        }catch (Exception e){
            e.printStackTrace();
        }
        return resp;

    }

    @RequestMapping(value = "info")
    @ResponseBody
    public Object info(){
        BaseResp resp = new BaseResp();
        try{
            resp.setData(ShiroUtils.getUserEntity());
        }catch (Exception e){
            e.printStackTrace();
        }
        return resp;

    }

}
